import QtQuick 2.15
import QtQuick.Controls 2.15
import QtQuick.Layouts 1.15
import QtQuick.Controls.Material 2.15
import QtGraphicalEffects 1.15
import "../components" 1.0
import "../pages" 1.0

Page {
    id: monitorPage
    readonly property int cmd_loop_move: 2010 //开环运动
    readonly property int cmd_loop_stop: 2000 //停止开环运动
    readonly property int cmd_ctrl_relocation: 2002 //重定位
    readonly property int cmd_nav_move: 3055 //平动
    readonly property int cmd_nav_rotate: 3056 //转动
    readonly property int cmd_get_contorl_authority: 4005 //获取控制权
    readonly property int cmd_soft_emergency_stop: 6004 //软急停
    readonly property int cmd_clear_alsrm: 4009 //清除所有报警

    property string robotId: ""
    property string robotIP: ""
    property string seerIP: ""
    property string cameraUrl: ""
    property var stackView: null
    property var robotCapabilities: []  // 添加机器人功能类型列表属性

    //SRC2000电池、位置、导航状态
    property var batteryValue: "85%"
    property var positionValueX: "0.0"
    property var positionValueY: "0.0"
    property var statusValue: "未知"
    property var statusColor: "green"

    //传感器数据属性
    property string airTemperature: "24.5℃"
    property string airHumidity: "65%"
    property string lightIntensity: "850 lux"
    property string co2Concentration: "450 ppm"
    property string soilTemperature: "0.0℃"
    property string soilMoisture: "0.0%"

    // 开环运动参数属性
    property double moveVx: 0.2    //机器人坐标系下 X 方向运动的速度, 正为向前, 负为向后, 单位: m/s
    property double moveVy: 0.0    //机器人坐标系下 Y 方向运动的速度, 正为向左, 负为向右, 单位: m/s
    property double rotateVw: 0.3  //转动角速度

    /**
     * 提示信息管理器
     */
    ToastManager {
        id: toastManager
    }

    // 创建导航控制参数数据库表
    function createNavigationParamsTable() {
        var columns = "robot_id TEXT PRIMARY KEY, " +
                    "move_vx REAL DEFAULT 0.5, " +
                    "move_vy REAL DEFAULT 0.0, " +
                    "rotate_vw REAL DEFAULT 0.5"
        databaseManager.createTable("navCtrl_params", columns)
    }

    // 5秒后自动释放软急停功能
    Timer {
        id: softEmergencyStopTimer
        interval: 60000  // 1分钟
        repeat: false
        onTriggered: {
            robotController.softEmergencyStop(cmd_soft_emergency_stop, false)
        }
    }

    // 从数据库加载导航控制参数
    function loadNavigationParams() {
        if (monitorPage.robotId) {
            var conditions = {"robot_id": monitorPage.robotId}
            var result = databaseManager.selectRecord("navCtrl_params", conditions)
            
            if (result && Object.keys(result).length > 0) {
                monitorPage.moveVx = result.move_vx || 0.5
                monitorPage.moveVy = result.move_vy || 0.0
                monitorPage.rotateVw = result.rotate_vw || 0.5
            }
        }
    }

    // 保存导航控制参数到数据库中
    function saveNavigationParams() {
        if (monitorPage.robotId) {
            var data = {
                "robot_id": monitorPage.robotId,
                "move_vx": monitorPage.moveVx,
                "move_vy": monitorPage.moveVy,
                "rotate_vw": monitorPage.rotateVw
            }
            databaseManager.insertOrUpdate("navCtrl_params", data, "robot_id")
        }
    }

    //请求返回上一页
    signal requestBack()

    Connections {
        target: heartbeatModel
        function onRobotStatusUpdated(robotId, status, currentTarget, battery, x, y) {
            // 检查机器人ID
            if (robotId === monitorPage.robotId) {
                // 更新电池信息
                batteryValue = (battery > 0) ? battery + "%" : "N/A"

                // 更新位置信息
                positionValueX = x.toFixed(2)
                positionValueY = y.toFixed(2)

                // 更新导航状态
                statusValue = status + (currentTarget ? "→" + currentTarget : "")
                statusColor = status === "RUNNING" ? "#4CAF50" :
                             status === "FAILED" ? "#F44336" : "#FFC107"
            }
        }
    }

    // 连接传感器数据更新信号
    Connections {
        target: sensorSubscriber
        function onSensorDataUpdated(robotId, airTemperature, airHumidity, lightIntensity,
                                    co2Concentration, soilTemperature, soilMoisture) {
            /*
            console.log("QML接收到传感器数据，来自机器人:", robotId)
            console.log("  空气温度:", airTemperature)
            console.log("  空气湿度:", airHumidity)
            console.log("  光照强度:", lightIntensity)
            console.log("  CO2浓度:", co2Concentration)
            console.log("  土壤温度:", soilTemperature)
            console.log("  土壤湿度:", soilMoisture)
            */
            // 检查是否是我们关注的机器人
            if (robotId === monitorPage.robotId) {
                // 更新属性
                monitorPage.airTemperature = airTemperature
                monitorPage.airHumidity = airHumidity
                monitorPage.lightIntensity = lightIntensity
                monitorPage.co2Concentration = co2Concentration
                monitorPage.soilTemperature = soilTemperature
                monitorPage.soilMoisture = soilMoisture
            } else {
                console.log("收到其他机器人的数据，忽略:", robotId)
            }
        }
    }

    Connections {
        target: robotController
    }

    /*
    //注释掉使用旧版RobotController数据接口获取机器人状态
    Connections {
        target: robotController
        function onBatteryUpdated(level) {
            batteryValue = (level > 0) ? (level * 100).toFixed(0) + "%" : "N/A"
        }
    }

    Connections {
        target: robotController
        function onPositionUpdated(x, y, angle) {
            positionValueX = x.toFixed(2)
            positionValueY = y.toFixed(2)
            //compass.rotation = angle // 直接控制指南针控件
        }
    }

    Connections {
        target: robotController
        function onNavigationStateUpdated(state, target) {
            statusValue = state + (target ? "→" + target : "")
            statusColor = state === "RUNNING" ? "#4CAF50" :
                         state === "FAILED" ? "#F44336" : "#FFC107"
        }
    }
    */
    Component.onCompleted: {
        console.log("----> seerIP: " + seerIP + ", robotIP: " + robotIP + ", cameraUrl: " + cameraUrl);
        if (monitorPage.seerIP) {
            robotController.connectRobot(monitorPage.seerIP,monitorPage.robotIP)    // 连接SRC2000和Jetson控制板
            robotController.setParameters(monitorPage.robotId)     // 设置robotId以备下载map资源到对应robot目录等
            console.log("Connecting robot at:", monitorPage.seerIP)
        } else {
            console.warn("seerIP is empty!")
        }
        
        // 设置传感器订阅器的机器人ID
        if (typeof sensorSubscriber !== "undefined" && sensorSubscriber) {
            sensorSubscriber.setNamespace(monitorPage.robotId);
        }
        
        // 检查数据库是否已经初始化
        if (typeof databaseManager !== "undefined" && databaseManager) {
            // 如果有isInitialized方法，先检查是否已初始化
            if (typeof databaseManager.isInitialized === "function") {
                if (!databaseManager.isInitialized()) {
                    databaseManager.initialize("rms_master.db")
                }
            } else {
                // 如果没有isInitialized方法，直接尝试初始化（可能产生警告但不会出错）
                try {
                    databaseManager.initialize("rms_master.db")
                } catch (e) {
                    console.log("数据库可能已经初始化:", e)
                }
            }
            
            // 确保导航参数表存在
            createNavigationParamsTable()
            // 加载当前机器人的参数
            loadNavigationParams()
        }
    }

    Component.onDestruction:{
        if (typeof robotController !== "undefined" && robotController) {
            robotController.disconnectRobot()  //断开SRC2000连接
        }
        
        // 关闭数据库连接
        if (typeof databaseManager !== "undefined" && databaseManager) {
            if (typeof databaseManager.close === "function") {
                databaseManager.close()
            }
        }

         // 清理传感器订阅器
        if (typeof sensorSubscriber !== "undefined" && sensorSubscriber) {
            sensorSubscriber.stop()
        }
    }
    

    // ===== 顶部导航工具栏 =====
    header: ToolBar {
        id: navBar
        property int currentIndex: 0  // 默认选中"机器监控"
        Material.background: Material.color(Material.Grey, Material.Shade100)
        Material.elevation: 4
        layer.enabled: true
        layer.effect: DropShadow {
            color: "#40000000"
            radius: 8
            samples: 16
            verticalOffset: 2
        }

        RowLayout {
            anchors.fill: parent
            spacing: 0

            // 返回按钮（左侧）
            ToolButton {
                icon.source: "qrc:///icons/back.svg"
                icon.color: "black"
                onClicked: {
                    if (stackView) stackView.pop()
                    else if (StackView.view) StackView.view.pop()
                    else requestBack()
                }
            }

            // 导航选项（居中）
            Repeater {
                model: ["机器监控", "地图视图", "任务链条","日志查看"]
                delegate: Button {
                    Layout.fillWidth: true
                    Layout.preferredHeight: 38
                    Layout.maximumWidth: 180

                    background: Rectangle {
                        radius: 4
                        color: navBar.currentIndex === index ?
                            Material.accent : Material.background
                        border.color: Material.color(Material.Grey, Material.Shade300)

                        layer.enabled: navBar.currentIndex === index
                        layer.effect: DropShadow {
                            color: "#20000000"
                            radius: 6
                            samples: 12
                        }
                    }

                    contentItem: Text {
                        text: modelData
                        horizontalAlignment: Text.AlignHCenter
                        verticalAlignment: Text.AlignVCenter  // 垂直居中对齐
                        elide: Text.ElideRight  // 文本省略处理
                        color: navBar.currentIndex === index ?
                            "white" : Material.color(Material.Grey, Material.Shade800)
                        font.bold: navBar.currentIndex === index
                        font.pixelSize: 14  // 明确设置字体大小
                    }

                    onClicked: {
                        navBar.currentIndex = index
                        if (index === 0) innerStackView.replace(monitorContent)
                        else if (index === 1) innerStackView.replace(mapViewerPage)
                        else if (index === 2) innerStackView.replace(taskChainPage)
                        else if (index === 3) innerStackView.replace(robotLogsPage)
                    }
                }
            }

            // 空白区域填充（右侧）
            Item { Layout.fillWidth: true }

            // 急停按钮
            RoundButton {
                id: emergencyStopToolbarButton
                text: "停"
                font.bold: true
                Material.foreground: "white"
                //icon.source: "qrc:/icons/emergency_stop.png"
                icon.color: "white"
                icon.width: 24
                icon.height: 24
                Layout.preferredWidth: 48
                Layout.preferredHeight: 48
                Layout.margins: 4
                flat: false

                background: Rectangle {
                    color: emergencyStopToolbarButton.down ? "#D32F2F" : "#F44336"
                    radius: 24
                    border.color: "#B71C1C"
                    border.width: 1
                }

                onPressed: {
                    // 如果定时器正在运行，重置定时器
                    if (softEmergencyStopTimer.running) {
                        softEmergencyStopTimer.restart()  // 重置定时器
                        return
                    }
                    robotController.softEmergencyStop(cmd_soft_emergency_stop, true)    // 发送软急停命令
                }

                onReleased: {
                    // 启动定时器，5秒后释放软急停功能
                    softEmergencyStopTimer.start()
                }

                ToolTip.text: "急停"
                ToolTip.visible: hovered
                ToolTip.delay: 1000
            }

            // 抢占控制权按钮
            RoundButton {
                id: acquireControlAuthorityButton
                text: acquireControlAuthorityButton.hasControlAuthority ? "有" : "无"
                font.bold: true
                Material.background: acquireControlAuthorityButton.hasControlAuthority ? "green" : "red"
                Material.foreground: "white"
                icon.color: "white"
                icon.width: 24
                icon.height: 24
                Layout.preferredWidth: 48
                Layout.preferredHeight: 48
                Layout.margins: 4
                flat: false

                 property bool hasControlAuthority: false
                    property string controlOwner: ""

                    // 初始状态为绿色（拥有控制权）
                    Component.onCompleted: {
                        hasControlAuthority = true
                        controlOwner = ""
                    }

                    // 连接控制权状态更新信号
                    Connections {
                        target: robotController
                        function onControlAuthorityUpdated(hasAuthority, owner) {
                            acquireControlAuthorityButton.hasControlAuthority = hasAuthority
                            acquireControlAuthorityButton.controlOwner = owner

                            // 如果 owner 是当前客户端名称，则强制设置为拥有控制权
                            if (owner === monitorPage.robotId) {
                                acquireControlAuthorityButton.hasControlAuthority = true
                            }
                            console.log("控制权状态更新 - 有控制权:", acquireControlAuthorityButton.hasControlAuthority, "所有者:", owner)
                        }
                    }

                    onClicked: {
                        // 如果没有控制权，点击按钮抢占控制权
                        if (!acquireControlAuthorityButton.hasControlAuthority) {
                            console.log("尝试抢占控制权")
                            robotController.acquireControlAuthority(monitorPage.robotId, cmd_get_contorl_authority)
                        }
                    }

                    // 监听操作完成信号，如果抢占控制权操作成功，则更新本地状态
                    Connections {
                        target: robotController
                        function onOperationCompleted(cmdId, success) {
                            // 如果是抢占控制权的操作且成功了，则更新本地状态
                            if (cmdId === cmd_get_contorl_authority && success) {
                                acquireControlAuthorityButton.hasControlAuthority = true
                                acquireControlAuthorityButton.controlOwner = ""
                                toastManager.show("成功抢占控制权")
                            }
                        }
                    }

                    ToolTip.text: acquireControlAuthorityButton.hasControlAuthority ? 
                                "拥有控制权" :
                                (acquireControlAuthorityButton.controlOwner ?
                                "控制权属于: " + acquireControlAuthorityButton.controlOwner :
                                "无控制权")
                    ToolTip.visible: acquireControlAuthorityButton.hovered
                    ToolTip.delay: 500
            }

            // 重定位按钮
            RoundButton {
                id: relocationButton
                text: "定"
                font.bold: true
                //icon.source: "qrc:/icons/relocation.png"
                icon.color: "white"
                icon.width: 24
                icon.height: 24
                Layout.preferredWidth: 48
                Layout.preferredHeight: 48
                Layout.margins: 4
                flat: false

                background: Rectangle {
                    color: relocationButton.down ? "#1976D2" : "#2196F3"
                    radius: 24
                    border.color: "#0D47A1"
                    border.width: 1
                }

                contentItem: Text {
                    text: relocationButton.text
                    font: relocationButton.font
                    opacity: enabled ? 1.0 : 0.3
                    color: "white"
                    horizontalAlignment: Text.AlignHCenter
                    verticalAlignment: Text.AlignVCenter
                    elide: Text.ElideRight
                }

                onClicked: {
                    robotController.relocation(cmd_ctrl_relocation) // 发送重定位命令
                }

                ToolTip.text: "重定位"
                ToolTip.visible: hovered
                ToolTip.delay: 1000
            }

            // 报警数量显示按钮（右侧）
            ToolButton {
                id: warningButton
                property int warningCount: 0
                property var warningDetails: [] // 存储警告详细信息

                // 连接报警状态更新信号
                Connections {
                    target: robotController
                    function onRobotAlarmStatusUpdated(statusJson) {
                        //console.log("收到报警状态更新: " + statusJson);
                        try {
                            // 解析JSON数据以获取报警和错误数量
                            var statusObj = JSON.parse(statusJson);
                            warningButton.warningCount = statusObj.warnings ? statusObj.warnings.length : 0;
                            warningButton.warningDetails = statusObj.warnings || [];
                            console.log("警告数量: " + warningButton.warningCount);
                        } catch (e) {
                            console.log("解析报警状态JSON失败: " + e);
                        }
                    }
                }

                text: "⚠ " + warningButton.warningCount
                visible: warningButton.warningCount > 0
                font.bold: true
                Material.foreground: "#FF9800"  // 橙色
                onClicked: {
                    // 显示报警详细信息对话框
                    alarmDetailsDialog.currentIndex = 0; // 切换到警告标签页
                    alarmDetailsDialog.open();
                }
            }

            // 错误数量显示按钮（右侧）
            ToolButton {
                id: errorButton
                property int errorCount: 0
                property var errorDetails: [] // 存储错误详细信息

                // 连接报警状态更新信号
                Connections {
                    target: robotController
                    function onRobotAlarmStatusUpdated(statusJson) {
                        //console.log("收到报警状态更新: " + statusJson);
                        try {
                            // 解析JSON数据以获取错误数量
                            var statusObj = JSON.parse(statusJson);
                            errorButton.errorCount = statusObj.errors ? statusObj.errors.length : 0;
                            errorButton.errorDetails = statusObj.errors || [];
                            console.log("错误数量: " + errorButton.errorCount);
                        } catch (e) {
                            console.log("解析报警状态JSON失败: " + e);
                        }
                    }
                }

                text: "❌ " + errorButton.errorCount
                visible: errorButton.errorCount > 0
                font.bold: true
                Material.foreground: "#F44336"  // 红色
                onClicked: {
                    // 显示报警详细信息对话框
                    alarmDetailsDialog.currentIndex = 1; // 切换到错误标签页
                    alarmDetailsDialog.open();
                }
            }
        }
    }

    // ===== 页面内容区域 =====
    StackView {
        id: innerStackView
        anchors.fill: parent
        anchors.margins: 15
        // 初始页面延迟加载
        Component.onCompleted: replace(monitorContent)

        // 页面切换动画
        pushEnter: Transition {
            PropertyAnimation {
                property: "opacity"
                from: 0
                to: 1
                duration: 300
            }
        }
        popExit: Transition {
            PropertyAnimation {
                property: "opacity"
                from: 1
                to: 0
                duration: 300
            }
        }
    }

    // ===== 页面组件定义 =====
    Component {
        id: monitorContent

        GridLayout {
            width: innerStackView.width
            height: innerStackView.height
            anchors.margins: 15   // 保留边距
            columns: 2
            columnSpacing: 20
            rowSpacing: 20

            // === 区域1：摄像头控制 ===
            Rectangle {
                id: cameraArea
                Layout.fillWidth: true
                Layout.fillHeight: true
                Layout.columnSpan: 1
                radius: 12
                color: "#21252B"
                clip: true

                // 摄像头预览占位符
                Rectangle {
                    id: cameraPlaceholder
                    anchors.fill: parent
                    anchors.margins: 10
                    color: "#2C313A"
                    radius: 8
                    visible: !cameraLoader.active

                    Column {
                        anchors.centerIn: parent
                        spacing: 20

                        Image {
                            source: "qrc:///icons/camera.png"
                            anchors.horizontalCenter: parent.horizontalCenter
                            width: 80
                            height: 80
                        }

                        Text {
                            text: "点击开启摄像头预览"
                            color: "#ABB2BF"
                            font.pixelSize: 18
                            anchors.horizontalCenter: parent.horizontalCenter
                        }
                    }

                    MouseArea {
                        anchors.fill: parent
                        onClicked: {
                            cameraLoader.active = true
                            if (cameraLoader.item) {
                                cameraLoader.item.initCamera()
                            }
                            mouse.accepted = false
                        }
                        propagateComposedEvents: true
                    }
                }

                // 摄像头加载器
                Loader {
                    id: cameraLoader
                    anchors.fill: parent
                    active: false
                    sourceComponent: RtspCamera {
                        id: cameraControl
                        anchors.fill: parent
                        robotId: monitorPage.robotId
                        cameraUrl: monitorPage.cameraUrl
                    }
                }
            }

            // === 区域2：传感器数据 ===
            Rectangle {
                id: sensorArea
                Layout.fillWidth: true
                Layout.fillHeight: true
                radius: 12
                color: "#21252B"

                ColumnLayout {
                    anchors.fill: parent
                    anchors.margins: 15
                    Layout.fillWidth: true
                    Layout.fillHeight: true
                    spacing: 10

                    Text {
                        text: "环境传感器数据"
                        color: "white"
                        font.bold: true
                        font.pixelSize: 18
                        Layout.alignment: Qt.AlignHCenter
                    }

                    // 传感器网格
                    GridLayout {
                        Layout.fillWidth: true
                        Layout.fillHeight: true
                        columns: 2
                        rowSpacing: 15
                        columnSpacing: 20

                        SensorCard {
                            Layout.fillWidth: true
                            Layout.fillHeight: true
                            title: "空气温度"
                            value: monitorPage.airTemperature
                            icon: "qrc:/icons/temp.png"
                        }

                        SensorCard {
                            Layout.fillWidth: true
                            Layout.fillHeight: true
                            title: "空气湿度"
                            value: monitorPage.airHumidity
                            icon: "qrc:/icons/humidity.png"
                        }

                        SensorCard {
                            Layout.fillWidth: true
                            Layout.fillHeight: true
                            title: "光照强度"
                            value: monitorPage.lightIntensity
                            icon: "qrc:/icons/light.png"
                        }

                        SensorCard {
                            Layout.fillWidth: true
                            Layout.fillHeight: true
                            title: "CO₂浓度"
                            value: monitorPage.co2Concentration
                            icon: "qrc:/icons/co2.png"
                        }

                        SensorCard {
                            Layout.fillWidth: true
                            Layout.fillHeight: true
                            title: "土壤温度"
                            value: monitorPage.soilTemperature
                            icon: "qrc:/icons/soil-temp.png"
                        }

                        SensorCard {
                            Layout.fillWidth: true
                            Layout.fillHeight: true
                            title: "土壤湿度"
                            value: monitorPage.soilMoisture
                            icon: "qrc:/icons/soil-moisture.png"
                        }
                    }
                }
            }

            // === 区域3：状态信息 ===
            Rectangle {
                id: statusArea
                Layout.fillWidth: true
                Layout.preferredHeight: 150
                radius: 12
                color: "#21252B"

                RowLayout {
                    anchors.fill: parent
                    anchors.margins: 15
                    spacing: 20

                    StatusIndicator {
                        title: "电量"
                        value: batteryValue
                        icon: "qrc:/icons/battery.png"
                        progress: batteryValue ? parseFloat(batteryValue) / 100.0 : 0.85
                        property double batteryLevel: batteryValue ? parseFloat(batteryValue) : 85
                        statusColor: batteryLevel < 20 ? "#F44336" : "#4CAF50"
                    }

                    StatusIndicator {
                        title: "位置"
                        value: "X: " + positionValueX + " Y: " + positionValueY
                        icon: "qrc:/icons/location.png"
                    }

                    StatusIndicator {
                        title: "导航状态"
                        value: statusValue
                        icon: "qrc:/icons/status.png"
                        statusColor: statusColor
                    }
                }
            }

            // === 区域4：导航控制区域 ===
            Rectangle {
                id: navigationControlArea
                Layout.fillWidth: true
                Layout.preferredHeight: 150
                radius: 12
                color: "#21252B"
                // 导航控制标签
                Text {
                    id: navigationLabel
                    text: "导航控制"
                    color: "#ABB2BF"
                    font.pixelSize: 16
                    font.bold: true
                    anchors.left: parent.left
                    anchors.top: parent.top
                    anchors.margins: 15
                }
/*
                // 急停按钮
                RoundButton {
                    id: emergencyStopButton
                    width: 80
                    height: 80
                    text: "急停"
                    anchors.right: parent.right
                    anchors.bottom: parent.bottom
                    anchors.margins: 15
                    font.pixelSize: 16
                    font.bold: true
                    Material.background: Material.Red
                    Material.foreground: "black"  //文本字体颜色
                    
                    // 添加阴影效果使按钮更醒目
                    layer.enabled: true
                    layer.effect: DropShadow {
                        radius: 10
                        samples: 20
                        color: "#80FF0000"
                    }
                    
                    onPressed: {
                        // 如果定时器正在运行，重置定时器
                        if (softEmergencyStopTimer.running) {
                            softEmergencyStopTimer.restart()  // 重置定时器
                            return
                        }
                        robotController.softEmergencyStop(cmd_soft_emergency_stop,true)
                    }

                    onReleased: {
                        // 启动定时器，5秒后释放软急停功能
                        softEmergencyStopTimer.start()
                    }
                }

                // 控制权状态按钮
                RoundButton {
                    id: controlAuthorityButton
                    width: 35
                    height: 35
                    text: controlAuthorityButton.hasControlAuthority ? "有" : "无"
                    anchors.right: parent.right
                    anchors.top: parent.top
                    anchors.margins: 15
                    Material.background: controlAuthorityButton.hasControlAuthority ? "green" : "red"
                    
                    property bool hasControlAuthority: false
                    property string controlOwner: ""
                    
                    // 初始状态为绿色（拥有控制权）
                    Component.onCompleted: {
                        hasControlAuthority = true
                        controlOwner = ""
                    }
                    
                    // 连接控制权状态更新信号
                    Connections {
                        target: robotController
                        function onControlAuthorityUpdated(hasAuthority, owner) {
                            controlAuthorityButton.hasControlAuthority = hasAuthority
                            controlAuthorityButton.controlOwner = owner

                            // 如果 owner 是当前客户端名称，则强制设置为拥有控制权
                            if (owner === monitorPage.robotId) {
                                controlAuthorityButton.hasControlAuthority = true
                            }
                            console.log("控制权状态更新 - 有控制权:", controlAuthorityButton.hasControlAuthority, "所有者:", owner)
                        }
                    }
                    
                    onClicked: {
                        // 如果没有控制权，点击按钮抢占控制权
                        if (!controlAuthorityButton.hasControlAuthority) {
                            console.log("尝试抢占控制权")
                            robotController.acquireControlAuthority(monitorPage.robotId, cmd_get_contorl_authority)
                        }
                    }

                    // 监听操作完成信号，如果抢占控制权操作成功，则更新本地状态
                    Connections {
                        target: robotController
                        function onOperationCompleted(cmdId, success) {
                            // 如果是抢占控制权的操作且成功了，则更新本地状态
                            if (cmdId === cmd_get_contorl_authority && success) {
                                controlAuthorityButton.hasControlAuthority = true
                                controlAuthorityButton.controlOwner = ""
                                toastManager.show("成功抢占控制权")
                            }
                        }
                    }
                    
                    ToolTip.text: controlAuthorityButton.hasControlAuthority ? 
                                "拥有控制权" :
                                (controlAuthorityButton.controlOwner ?
                                "控制权属于: " + controlAuthorityButton.controlOwner :
                                "无控制权")
                    ToolTip.visible: controlAuthorityButton.hovered
                    ToolTip.delay: 500
                }
*/
            // 圆形云台控制按钮组 - 居中显示
            Item {
                    id: controlPanel
                    width: 150
                    height: 150
                    anchors.centerIn: parent
                    
                    // 定义持续控制按钮组件
                    Component {
                        id: continuousControlButton
                        
                        RoundButton {
                            id: controlButton
                            property string controlType: "move" // "move" 或 "rotate"
                            property string direction: "up"
                            property real moveVx: monitorPage.moveVx // 直接绑定到全局属性
                            property real moveVy: monitorPage.moveVy
                            property real rotateVw: monitorPage.rotateVw

                            // 定时器用于重复发送命令
                            Timer {
                                id: repeatTimer
                                interval: 500  // 500毫秒间隔
                                repeat: true
                                onTriggered: {
                                    if (controlButton.controlType === "move") {
                                        if(controlButton.direction === "up"){
                                            robotController.startLoopMoveRobot(controlButton.moveVx, 0,0, cmd_loop_move)
                                        }else if(controlButton.direction === "down"){
                                            robotController.startLoopMoveRobot(-controlButton.moveVx, 0,0, cmd_loop_move)
                                        }
                                    } else if (controlButton.controlType === "rotate") {
                                        if(controlButton.direction === "left"){
                                            robotController.startLoopMoveRobot(0, 0,controlButton.rotateVw, cmd_loop_move)
                                        }else if(controlButton.direction === "right"){
                                            robotController.startLoopMoveRobot(0, 0,-controlButton.rotateVw, cmd_loop_move)
                                        }
                                    }
                                }
                            }
                            
                            onPressed: {
                                // 根据控制类型和方向发送相应的命令
                                if (controlType === "move") {
                                    if (direction === "up") {
                                        robotController.startLoopMoveRobot(moveVx, moveVy, 0, cmd_loop_move)
                                    } else if(direction === "down"){
                                        robotController.startLoopMoveRobot(-moveVx, -moveVy, 0, cmd_loop_move)
                                    }

                                } else if (controlType === "rotate") {
                                    if (direction === "left") {
                                        robotController.startLoopMoveRobot(0, 0, rotateVw, cmd_loop_move)
                                    }else if(direction === "right"){
                                        robotController.startLoopMoveRobot(0, 0, -rotateVw, cmd_loop_move)
                                    }
                                }
                                
                                // 启动重复定时器，持续发送命令
                                repeatTimer.start()
                            }
                            
                            onReleased: {
                                // 停止定时器
                                repeatTimer.stop()
                                
                                // 发送停止命令
                                robotController.stopLoopMoveRobot(cmd_loop_stop)
                                /*
                                if (controlType === "move") {
                                    robotController.stopLoopMoveRobot(cmd_loop_stop)
                                } else if (controlType === "rotate") {
                                    robotController.stopLoopMoveRobot(cmd_loop_stop)
                                }
                                */
                            }
                            
                            Component.onDestruction: {
                                // 确保定时器停止
                                if (repeatTimer.running) {
                                    repeatTimer.stop()
                                }
                            }
                            
                            Material.background: Material.Blue
                        }
                    }
                    
                    // 圆形容器
                    Rectangle {
                        id: circleBackground
                        anchors.fill: parent
                        radius: width / 2
                        color: "#40000000"  // 半透明背景
                        
                        // 上按钮
                        Loader {
                            id: upButton
                            width: 40
                            height: 40
                            anchors.horizontalCenter: parent.horizontalCenter
                            anchors.top: parent.top
                            anchors.topMargin: 10
                            
                            sourceComponent: continuousControlButton
                            
                            onLoaded: {
                                item.text = "↑"
                                item.controlType = "move"
                                item.direction = "up"
                            }
                        }

                        // 左按钮
                        Loader {
                            id: leftButton
                            width: 40
                            height: 40
                            anchors.verticalCenter: parent.verticalCenter
                            anchors.left: parent.left
                            anchors.leftMargin: 10
                            
                            sourceComponent: continuousControlButton
                            
                            onLoaded: {
                                item.text = "←"
                                item.controlType = "rotate"
                                item.direction = "left"
                            }
                        }
                        
                        // 设置按钮（中间）
                        RoundButton {
                            id: settingButton
                            width: 50
                            height: 50
                            anchors.centerIn: parent
                            text: "⚙"
                            onClicked: {
                                // 设置对话框显示默认值
                                moveVxField.text = monitorPage.moveVx.toString()
                                moveVyField.text = monitorPage.moveVy.toString()
                                
                                rotateVwField.text = monitorPage.rotateVw.toString()
                                
                                navSettingDialog.open()
                            }
                            Material.background: Material.Green
                        }
                        
                        // 右按钮
                        Loader {
                            id: rightButton
                            width: 40
                            height: 40
                            anchors.verticalCenter: parent.verticalCenter
                            anchors.right: parent.right
                            anchors.rightMargin: 10
                            
                            sourceComponent: continuousControlButton
                            
                            onLoaded: {
                                item.text = "→"
                                item.controlType = "rotate"
                                item.direction = "right"
                            }
                        }

                        // 下按钮
                        Loader {
                            id: downButton
                            width: 40
                            height: 40
                            anchors.horizontalCenter: parent.horizontalCenter
                            anchors.bottom: parent.bottom
                            anchors.bottomMargin: 10
                            
                            sourceComponent: continuousControlButton
                            
                            onLoaded: {
                                item.text = "↓"
                                item.controlType = "move"
                                item.direction = "down"
                            }
                        }
                    }
                }
            }
        }
    }

    // === 地图视图组件 ===
    Component {
        id: mapViewerPage
        MapViewerPage {
            width: innerStackView.width
            height: innerStackView.height
            robotId: monitorPage.robotId
            currentMapName: robotController.getCurrentMapName()
        }

    }

    // === 任务链条组件 ===
    Component {
        id: taskChainPage
        TaskChainPage {
            width: innerStackView.width
            height: innerStackView.height
            robotId: monitorPage.robotId
            robotCapabilities: monitorPage.robotCapabilities  // 传递机器人功能类型列表
        }
    }

    // === 日志组件(占位) ===
    Component {
        id: robotLogsPage
        RobotLogsPage {
            width: innerStackView.width
            height: innerStackView.height
            robotId: monitorPage.robotId
        }
    }

    // ===== 导航设置对话框 =====
    Dialog {
        id: navSettingDialog
        title: "导航控制参数设置"
        modal: true
        standardButtons: Dialog.Ok | Dialog.Cancel
        anchors.centerIn: parent
        width: 450

        ScrollView {
            anchors.fill: parent
            clip: true
            
            ColumnLayout {
                anchors.fill: parent
                spacing: 15

            // 平动参数部分
                GroupBox {
                    title: "平动参数"
                    Layout.fillWidth: true
                    
                    GridLayout {
                        columns: 2
                        rowSpacing: 10
                        columnSpacing: 15
                        width: parent.width
                        
                        Text { 
                            text: "X速度(m/s):"; 
                            color: "black" 
                            horizontalAlignment: Text.AlignRight
                            Layout.minimumWidth: 100  // 设置最小宽度确保可见
                        }
                        TextField { 
                            id: moveVxField
                            Layout.fillWidth: true
                            validator: DoubleValidator {}
                        }
                        
                        Text { 
                            text: "Y速度(m/s):"; 
                            color: "black" 
                            horizontalAlignment: Text.AlignRight
                            Layout.minimumWidth: 100
                        }
                        TextField { 
                            id: moveVyField
                            Layout.fillWidth: true
                            validator: DoubleValidator {}
                        }
                    }
                }

                // 转动参数部分
                GroupBox {
                    title: "转动参数"
                    Layout.fillWidth: true
                    
                    GridLayout {
                        columns: 2
                        rowSpacing: 10
                        columnSpacing: 15
                        width: parent.width
                        
                        Text { 
                            text: "角速度(rad/s):"; 
                            color: "black" 
                            horizontalAlignment: Text.AlignRight
                            Layout.minimumWidth: 100
                        }
                        TextField { 
                            id: rotateVwField
                            Layout.fillWidth: true
                            validator: DoubleValidator {}
                        }
                    }
                }
            }
        }

        // onAccepted处理函数以保存参数到数据库
        onAccepted: {
            // 保存设置值到属性
            monitorPage.moveVx = parseFloat(moveVxField.text) || monitorPage.moveVx
            monitorPage.moveVy = parseFloat(moveVyField.text) || monitorPage.moveVy
            monitorPage.rotateVw = parseFloat(rotateVwField.text) || monitorPage.rotateVw
            
            // 保存到数据库
            saveNavigationParams()
            
            console.log("参数已更新并保存到数据库: 平动[Vx=" + monitorPage.moveVx + 
                    ", Vy=" + monitorPage.moveVy + 
                    "] 转动[角速度=" + monitorPage.rotateVw + "]")
            toastManager.show("参数已更新并保存到数据库")
        }
    }

    // 报警详细信息对话框
    Dialog {
        id: alarmDetailsDialog
        title: "报警详细信息"
        modal: true
        standardButtons: Dialog.Ok
        anchors.centerIn: parent
        width: Math.min(parent.width - 20, 400)
        height: Math.min(parent.height - 100, 300)

        property int currentIndex: 0 // 0表示警告，1表示错误

        ColumnLayout {
            anchors.fill: parent

            // 标签页控制器
            TabBar {
                id: alarmTabBar
                Layout.fillWidth: true

                TabButton {
                    text: "警告 (" + warningButton.warningCount + ")"
                    }
                    TabButton {
                        text: "错误 (" + errorButton.errorCount + ")"
                    }

                    onCurrentIndexChanged: {
                        alarmDetailsDialog.currentIndex = currentIndex;
                    }
                }

                // 标签页内容
                StackLayout {
                    Layout.fillWidth: true
                    Layout.fillHeight: true
                    currentIndex: alarmDetailsDialog.currentIndex

                    // 警告列表
                    Item {
                        ScrollView {
                            anchors.fill: parent

                            ListView {
                                id: warningListView
                                model: warningButton.warningDetails
                                delegate: Rectangle {
                                    width: parent.width
                                    height: 60
                                    color: index % 2 ? "#f0f0f0" : "#ffffff"
                                    border.color: "#ddd"

                                    Text {
                                        anchors.fill: parent
                                        anchors.margins: 5
                                        text: {
                                            var warning = modelData;
                                            var keys = Object.keys(warning);
                                            var code = keys.length > 0 ? keys[0] : "未知";
                                            return "警告码: " + code + "\n描述: " + (warning.describe || warning.desc || "无描述");
                                        }
                                            wrapMode: Text.Wrap
                                            font.pixelSize: 12
                                        }
                                    }
                                }
                            }
                        }

                    // 错误列表
                    Item {
                        ScrollView {
                            anchors.fill: parent

                            ListView {
                                id: errorListView
                                model: errorButton.errorDetails
                                delegate: Rectangle {
                                    width: parent.width
                                    height: 60
                                    color: index % 2 ? "#f0f0f0" : "#ffffff"
                                    border.color: "#ddd"

                                Text {
                                    anchors.fill: parent
                                    anchors.margins: 5
                                    text: {
                                        var error = modelData;
                                        var keys = Object.keys(error);
                                        var code = keys.length > 0 ? keys[0] : "未知";
                                        return "错误码: " + code + "\n描述: " + (error.describe || error.desc || "无描述");
                                    }
                                    wrapMode: Text.Wrap
                                    font.pixelSize: 12
                                }
                            }
                        }
                    }
                }
            }

            Button {
                text: "清除所有报警"
                Layout.fillWidth: true
                onClicked: {
                    robotController.clearRobotAlarms(cmd_clear_alsrm);
                    alarmDetailsDialog.close();
                    }
                Material.background: Material.Red
                }
            }

        onOpened: {
            // 同步标签页索引
            alarmTabBar.currentIndex = alarmDetailsDialog.currentIndex;
        }
    }
}
